#!/bin/bash

clean_sector_() {
  local sector="$1"
  local mdir="M${sector}"
  if [[ ! -d "$mdir" ]]; then
    echo "$0: Directory $mdir does not exist"
    return 1
  fi
  local dot_count=$(find "$mdir" -name "_*.dot" | wc -l)
  local pdf_count=$(find "$mdir" -name "_*.pdf" | wc -l)
  echo "$0: Cleaning $mdir/ (found ${dot_count} .dot files, ${pdf_count} .pdf files)"
  find "$mdir" -name "_*.dot" -type f -delete
  find "$mdir" -name "_*.pdf" -type f -delete
  echo "$0: Cleaned $mdir/"
}

if [[ -n "${m0sector}" && "${m0sector}" != "#" ]]; then # if run via FPS
  echo "$0: FPS mode processing ${m0type} ${m0sector} ${m0name} ${m0tier} ${m0version}"
  clean_sector_ "${m0sector}"
else # if run directly
  if [[ $# -ne 1 ]]; then
    echo "Usage: $0 <sector_number>" >&2
    echo "Or run via FPS: fps $0 mxxx.fps:run_number" >&2
    exit 1
  fi
  sector="$1"
  if [[ ! "$sector" =~ ^[0-9]+$ ]]; then
    echo "$0: Invalid sector number: $sector" >&2
    exit 1
  fi
  echo "$0: Direct mode cleaning sector $sector"
  clean_sector_ "$sector"
fi
